package com.sjtu.spi;

import com.sjtu.constants.ApiConstants;
import com.sjtu.form.JobResult;
import com.sjtu.zookeeper.InstanceDetails;
import com.sjtu.zookeeper.ServiceDiscoverUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * nerine
 * 2/6/2020
 */
@Slf4j
@Service
public class JobResultPushService {
    @Autowired
    private WebClient sjtuWebClient;
    /**
     * push
     * @param jobResult
     * @param jobName
     */
    public void push(JobResult jobResult, String jobName) {
        ServiceProvider<InstanceDetails> provider =
                ServiceDiscoverUtil.getServiceProvider(ApiConstants.SERVER_NAME);

        Mono<JobResult> mono = Mono.just(jobResult);
        try {
            Object result = sjtuWebClient.post()
                    .uri(concatHttpUrl(provider.getInstance()))
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(mono, JobResult.class)
                    .retrieve()
                    .bodyToMono(Object.class)
                    .block();
            log.info("push job {} result back, result is: {}", jobName, result);
        } catch (Exception e) {
            log.error("error in push job result back to server: ", e);
        }
    }

    String concatHttpUrl(ServiceInstance<InstanceDetails> serviceInstance) {
        return "http://" + serviceInstance.getAddress() + ":" + serviceInstance.getPort() + ApiConstants.SERVER_PUSH_BACK_URL;
    }
}
